from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.charts import Liquid, Page,Grid,Tab,Line
from pyecharts.globals import SymbolType
from pyecharts.globals import ThemeType
from pyecharts.components import Table
from pyecharts.options import ComponentTitleOpts
from util.database import DB_CONN
from util.stock_util import judge_code_trading_date,get_trading_dates,get_diff_dates,calc_negative_diff_dates,judge_code_trading_date
from datetime import datetime
from strategy.stock_pool.pattern_stock_pool import PatternStockPool
from strategy.stock_pool.value_stock_pool import ValueStockPool
from factor.factor_module import FactorModule
from monitor.best_block_monitor import BestBlockMonitor
import pandas as pd
import time
from pymongo import ASCENDING,DESCENDING
from pandas import DataFrame
from functools import reduce

class Visual:
    def __init__(self,begin_date,end_date,show_date):
        datetime_obj = datetime.now()
        cur_date = datetime_obj.strftime('%Y-%m-%d')
        cur_date = judge_code_trading_date(date=cur_date)
        cur_month_begin_date = f"{cur_date[:7]}-01"
        last_month_end_date = calc_negative_diff_dates(date=cur_month_begin_date,delta_days =-1)
        cur_year_begin_date = f"{cur_date[:4]}-01-01"
        last_year_end_date = f"{str(int(cur_date[:4])-1)}-12-31"

        if show_date is None:
            show_date = cur_date
        if begin_date is None:
            begin_date = '2017-10-17'
        if end_date is None:
            end_date = cur_date

        self.begin_date = begin_date
        self.end_date = end_date
        self.show_date = show_date
        self.cur_date = cur_date
        self.cur_month_begin_date = cur_month_begin_date
        self.last_month_end_date = last_month_end_date
        self.cur_year_begin_date = cur_year_begin_date
        self.last_year_end_date = last_year_end_date
        self.last_5_date = calc_negative_diff_dates(date=self.show_date,delta_days=-4)


    def get_date_holding(self,date):
        trading_date = judge_code_trading_date(date=date)
        daily_cursor = DB_CONN.date_holding.find({'date': trading_date},projection = {'_id': False})

        return daily_cursor[0]

    def get_total_date_holding(self,begin_date,end_date):
        daily_cursor = DB_CONN.date_holding.find({'date': {'$gte': begin_date, '$lte': end_date}},
                                                 sort=[('date', 1)],
                                                 projection = {'_id': False})
        return daily_cursor

    def get_trading_record(self,begin_date,end_date):
        daily_cursor = DB_CONN.trading_record.find({'sell_time': {'$gte': begin_date, '$lte': end_date}},
                                                 sort=[('sell_time', 1)],
                                                 projection = {'_id': False})
        return daily_cursor

    def get_pattern_strategy_stocks(self):
        psp= PatternStockPool("Pattern", None, None, 1)
        psp.get_option_stocks()
        daily_cursor = DB_CONN.pattern_strategy_option_stocks.find({'tracked': {'$gte': 1}},
                                                                 sort=[('find_date', 1)],
                                                                 projection = {'_id': False})
        return daily_cursor
 
    def get_value_strategy_stocks(self):
        vsp= ValueStockPool("Value", None, None, 1)
        vsp.get_option_stocks()
        daily_cursor = DB_CONN.value_strategy_option_stocks.find(sort=[('update_date', 1)],
                                                                 projection = {'_id': False})
        return daily_cursor

    def table_pattern_strategy_stocks(self):
        table = Table()
        pattern_strategy_stocks = self.get_pattern_strategy_stocks()
        rows = list()
        headers = ["代码",
                    "名称",
                    #"形态起始时间",
                    '首次突破时间',
                    '颈线位',
                    #"形态持续时间(天)",
                    #"形态顶部值",
                    # "形态底部值",
                    #"预期涨幅价",
                    # "止损价格",
                    #"预期涨幅比",
                    #"止损比",
                    #"风险收益比",
                    "20偏离比",
                    "颈线偏离比",
                    "RSI",
                    "ATR",
                    #'平均RS',
                    "rs_S_L_BS_BL_20",
                    "当日20偏离比",
                    "当日颈线偏离比",
                    "当日RSI",
                    "当日rs_S_L_BS_BL_20",
                    "多排",
                    "当日多排",
                    #"形态类型",
                    "c_行业",
                    "c_动量排名",
                    "c_动量值",
                    "c_当日动量排名",
                    "c_当日动量值",
                   ]
        for item in pattern_strategy_stocks:
            tmp_list = list()
            tmp_list.append(item['code'])
            tmp_list.append(item['name'])
            #tmp_list.append(item['pattern_begin_date'])
            tmp_list.append(item['find_date'])
            tmp_list.append(item['breaking_neck_value'])
            #tmp_list.append(item['diff_dates'])
            #tmp_list.append(item['up_value'])
            #tmp_list.append(item['down_value'])
            #tmp_list.append(item['expect_price'])
            #tmp_list.append(item['stop_loss_price'])
            #tmp_list.append(item['exp_ratio'])
            #tmp_list.append(item['stop_ratio'])
            #tmp_list.append(item['risk_reward_ratio'])
            tmp_list.append(item['bias_ma20_ratio'])
            tmp_list.append(item['bias_neck_value'])
            tmp_list.append(item['RSI_6'])
            tmp_list.append(item['atr_20'])
            #tmp_list.append(item['rs'])
            tmp_list.append(f"{item['short_rs']}_{item['long_rs']}_{item['block_short_rs']}_{item['block_long_rs']}_{item['rs_20']}")
            tmp_list.append(item['cur_bias_ma20_ratio'])
            tmp_list.append(item['cur_bias_neck_value'])
            tmp_list.append(item['cur_RSI_6'])
            tmp_list.append(f"{item['cur_short_rs']}_{item['cur_long_rs']}_{item['cur_block_short_rs']}_{item['cur_block_long_rs']}_{item['cur_rs_20']}")
            tmp_list.append(item['MA_up'])
            tmp_list.append(item['cur_MA_up'])
            #tmp_list.append(item['pattern_type'])
            tmp_list.append(item['choice_block_name'])
            tmp_list.append(item['choice_block_mom_rank'])
            tmp_list.append(item['choice_block_mom_value'])
            tmp_list.append(item['cur_choice_block_mom_rank'])
            tmp_list.append(item['cur_choice_block_mom_value'])
            rows.append(tmp_list)

        table.add(headers, rows).set_global_opts(
            title_opts=ComponentTitleOpts(title=f"近期形态学策略跟踪")
        )
        return table

    def table_value_strategy_stocks(self):
        table = Table()
        value_strategy_stocks = self.get_value_strategy_stocks()
        rows = list()
        headers = ["代码",
                    "名称",
                    '合理估值下限',
                    '合理估值上限',
                    '当前价格',
                    '当前价格偏离比',
                    "更新时间",
                    "来源",
                    "行业",
                    "类别",
                    "分析"]
        for item in value_strategy_stocks:
            tmp_list = list()
            tmp_list.append(item['code'])
            tmp_list.append(item['name'])
            tmp_list.append(item['low_price'])
            tmp_list.append(item['high_price'])
            tmp_list.append(item['cur_price'])
            tmp_list.append(item['bias_cur_price_ratio'])
            tmp_list.append(item['update_date'])
            tmp_list.append(item['source'])
            tmp_list.append(item['industry'])
            tmp_list.append(item['category'])
            tmp_list.append(item['analyze'])
            rows.append(tmp_list)

        table.add(headers, rows).set_global_opts(
            title_opts=ComponentTitleOpts(title=f"近期价值股跟踪")
        )
        return table

    def table_trading_record(self,begin_date,end_date) -> Table:
        table = Table()
        trading_record = self.get_trading_record(begin_date,end_date)
        rows = list()
        total_profit = 0
        date_holding = self.get_date_holding(end_date)

        headers = ["代码",
                   "名称",
                   "买入时间",
                   '卖出时间',
                   "持仓时间",
                   "收益",
                   "收益比例",
                   "平均买入价格",
                   "平均卖出价格",
                   "买入量",
                   "卖出量",
                   "成本",
                   '盈利预期'
                   #'分析'
                    ]
        for item in trading_record:
            tmp_list = list()
            tmp_list.append(item['code'])
            tmp_list.append(item['name'])
            tmp_list.append(item['buy_time'])
            tmp_list.append(item['sell_time'])
            tmp_list.append(item['holding_days'])
            tmp_list.append(item['profit'])
            tmp_list.append(item['profit_ratio'])
            tmp_list.append(item['buy_avg_price'])
            tmp_list.append(item['sell_avg_price'])
            tmp_list.append(item['buy_volume'])
            tmp_list.append(item['sell_volume'])
            tmp_list.append(item['cost'])
            tmp_list.append(item['expect_profit_ratio'])
            #tmp_list.append(item['analyze'])
            total_profit += item['profit']
            rows.append(tmp_list)

        #总计
        total_profit_ratio = round(100*total_profit/date_holding['total_value'],2)
        tmp_list = list()
        tmp_list.append('总计')
        tmp_list.append('N/A')
        tmp_list.append(begin_date)
        tmp_list.append(end_date)
        tmp_list.append('N/A')
        tmp_list.append(total_profit)
        tmp_list.append(total_profit_ratio)
        tmp_list.append('N/A')
        tmp_list.append('N/A')
        tmp_list.append('N/A')
        tmp_list.append('N/A')
        tmp_list.append('N/A')
        tmp_list.append('N/A')
        #tmp_list.append('N/A')
        rows.append(tmp_list)

        table.add(headers, rows).set_global_opts(
            title_opts=ComponentTitleOpts(title=f"交易纪录列表，从{begin_date}到{end_date}:")
        )
        return table

    def table_best_block(self,end_date) -> Table:
        try:
            table = Table()

            begin_date_1 = calc_negative_diff_dates(date=end_date,delta_days=-1)
            best_block_df_1 = BestBlockMonitor().monitoring(begin_date_1,end_date)

            begin_date_5 = calc_negative_diff_dates(date=end_date,delta_days=-4)
            best_block_df_5 = BestBlockMonitor().monitoring(begin_date_5,end_date)

            begin_date_20 = calc_negative_diff_dates(date=end_date,delta_days=-19)
            best_block_df_20 = BestBlockMonitor().monitoring(begin_date_20,end_date)
            print(best_block_df_1.index.size,best_block_df_5.index.size,best_block_df_20.index.size)
            rows = list()
            headers = ["代码A", "名称A", "当日涨幅",'排名A',
                       "代码B", "名称B", "5日涨幅", '排名B',
                       "代码C", "名称C", "20日涨幅", '排名C']

            for index, row in best_block_df_1.iterrows():
                tmp_list = list()
                tmp_list.append(index) #code是索引
                tmp_list.append(row['name'])
                tmp_list.append(row['relative_ratio'])
                tmp_list.append(row['rank'])
                rows.append(tmp_list)

            idx = 0
            for index, row in best_block_df_5.iterrows():
                if idx >= len(rows):
                    for i in range(4):
                        rows[idx].append('N/A')
                rows[idx].append(index)
                rows[idx].append(row['name'])
                rows[idx].append(row['relative_ratio'])
                rows[idx].append(row['rank'])
                idx+=1

            if idx < len(rows):
                for i in range(len(rows) - idx):
                    for j in range(4):
                        rows[idx+i].append('N/A')
            idx = 0
            for index, row in best_block_df_20.iterrows():
                if idx >= len(rows):
                    for i in range(8):
                        rows[idx].append('N/A')
                rows[idx].append(index)
                rows[idx].append(row['name'])
                rows[idx].append(row['relative_ratio'])
                rows[idx].append(row['rank'])
                idx+=1
            if idx < len(rows):
                for i in range(len(rows) - idx):
                    for j in range(4):
                        rows[idx+i].append('N/A')


            table.add(headers, rows).set_global_opts(
                title_opts=ComponentTitleOpts(title=f"近期强势板块列表，截止到{end_date}:")
            )
        #print(rows)
        except:
            return False,table

        return True,table

    def table_best_block_choice(self,end_date) -> Table:
        try:
            table = Table()
            headers = ["排名",
                       '当日板块名称',
                       "当日板块动量值",
                       "-1日板块名称",
                       '-1日板块动量值',
                       "-2日板块名称",
                       '-2日板块动量值',
                       "-3日板块名称",
                       '-3日板块动量值',
                       "-4日板块名称",
                       '-4日板块动量值'
                       ]
            all_data_list = list()
            dates = [0,-1,-2,-3,-4]
            max_rows = 30
            for delta in dates:
                begin_date = calc_negative_diff_dates(date=end_date,delta_days=delta)
                #print(f"begin_date:{begin_date}")
                momentum_cursor = DB_CONN['momentum'].find(
                    {'date': begin_date, 'type': 'sub_industry', "origin": 'choice'},
                    sort=[('rank', ASCENDING)],
                    projection={'code_list': False, '_id': False})
                if momentum_cursor.count() > max_rows:
                    for i in range(0,max_rows):
                        all_data_list.append(momentum_cursor[i]['name'])
                        all_data_list.append(momentum_cursor[i]['momentum_value'])

            #print(all_data_list)

            rows = list()

            for i in range(0,max_rows):
                tmp_list = list()
                tmp_list.append(f'{i+1}')
                for j in range(0,len(dates)):
                    tmp_list.append(all_data_list[j*(max_rows*2)+i*2])
                    tmp_list.append(all_data_list[j*(max_rows*2)+i*2+1])

                rows.append(tmp_list)

            #print(rows)
            table.add(headers, rows).set_global_opts(
                title_opts=ComponentTitleOpts(title=f"choice近期强势板块列表，截止到{end_date}:")
            )
        #print(rows)
        except:
            return False,table

        return True,table

    def cal_avg_best_block_choice(self,end_date):
        dates = [0, -1, -2, -3, -4]
        max_rows = 30
        df_list = list()
        new_columns_list = list()
        for delta in dates:

            begin_date = calc_negative_diff_dates(date=end_date, delta_days=delta)
            momentum_cursor = DB_CONN['momentum'].find(
                {'date': begin_date, 'type': 'sub_industry', "origin": 'choice'},
                sort=[('rank', ASCENDING)],
                projection={'code_list': False, 'origin': False, 'type': False, 'rank': False, 'date': False,
                            '_id': False})
            if momentum_cursor.count() > max_rows:
                moment_df = DataFrame([x for x in momentum_cursor])
                moment_df.set_index(['name'], 1, inplace=True)
                df_list.append(moment_df.copy())

        # 逐个merge df
        df_final = reduce(lambda left, right: pd.merge(left, right, left_index=True, right_index=True, how='outer'),
                          df_list)
        for i in dates:
            new_columns_list.append(f'mom_v_{i}')

        # 修改为新的列名
        new_columns = pd.core.indexes.base.Index(new_columns_list)
        df_final.columns = new_columns
        df_final.fillna(0, inplace=True)
        # df_final.to_csv("df_final.csv")
        df_mean_ser = df_final.mean(1)
        df_final.insert(len(df_final.columns), 'avg_mov_v', df_mean_ser)
        df_final.insert(len(df_final.columns), 'name', df_final.index)
        sort_df = df_final.sort_values(by="avg_mov_v", ascending=False)
        print(sort_df.head(15))
        return sort_df

    def table_avg_best_block_choice(self,end_date):
        #try:
        table = Table()
        #print(sort_df)
        sort_df = self.cal_avg_best_block_choice(end_date)
        last_date = calc_negative_diff_dates(date=end_date, delta_days=-1)
        last_sort_df = self.cal_avg_best_block_choice(last_date)

        rows = list()
        i = 1

        headers = ["板块名称",
                   '排名',
                   '前一日排名',
                   '5日平均动量值',
                   "当日板块动量值",
                   '-1日板块动量值',
                   '-2日板块动量值',
                   '-3日板块动量值',
                   '-4日板块动量值'
                   ]
        for index,row in sort_df.iterrows():
            tmp_list = list()


            tmp_list.append(row['name'])
            tmp_list.append(i)

            j = 1
            for id,r in last_sort_df.iterrows():
                if row['name'] == r['name']:
                    tmp_list.append(j)
                    break
                j += 1
                if j > 16:
                    tmp_list.append('N/A')
                    break

            tmp_list.append(round(row['avg_mov_v'],2))
            tmp_list.append(round(row['mom_v_0'],2))
            tmp_list.append(round(row['mom_v_-1'],2))
            tmp_list.append(round(row['mom_v_-2'],2))
            tmp_list.append(round(row['mom_v_-3'],2))
            tmp_list.append(round(row['mom_v_-4'],2))
            i += 1
            if i > 16:
                break
            rows.append(tmp_list)

        table.add(headers, rows).set_global_opts(
            title_opts=ComponentTitleOpts(title=f"choice近5日均值强势板块列表，截止到{end_date}:")
        )

        # except Exception as e:
        #     print(f"table_avg_best_block_choice error:{e}")
#            return False,table

        return True,table

    def table_date_holding_part_1(self) -> Table:
        table = Table()
        date_holding = self.get_date_holding(self.show_date)
        rows = list()
        headers = ["代码",
                   "名称",
                   "个股仓位",
                   "买入时间",
                   "当前日期",
                   "持仓时间",
                   "收益",
                   "收益比例",
                   "平均买入价格",
                   "平均卖出价格",
                   "止损位置",
                   "止损价格",
                   "止损比例",
                   "当前价格",
                   "买入量",
                   "卖出量",
                   "持仓量",
                   "成本",
                   "当前市值",
                   "c_行业",
                   "c_动量排名",
                   "c_动量值",
                   ]
        for item in date_holding['code_holding']:
            tmp_list = list()
            tmp_list.append(item['code'])
            tmp_list.append(item['name'])
            tmp_list.append(item['code_position'])
            tmp_list.append(item['buy_time'])
            tmp_list.append(item['cur_time'])
            tmp_list.append(item['holding_days'])
            tmp_list.append(item['profit'])
            tmp_list.append(item['profit_ratio'])
            tmp_list.append(item['buy_avg_price'])
            tmp_list.append(item['sell_avg_price'])
            tmp_list.append(item['stop_profit_pos'])
            tmp_list.append(item['stop_profit_price'])
            tmp_list.append(item['stop_profit_ratio'])
            tmp_list.append(item['cur_price'])
            tmp_list.append(item['buy_volume'])
            tmp_list.append(item['sell_volume'])
            tmp_list.append(item['holding_volume'])
            tmp_list.append(item['cost'])
            tmp_list.append(item['cur_value'])
            tmp_list.append(item['sub_industry'])
            tmp_list.append(item['block_mom_rank'])
            tmp_list.append(item['block_mom_value'])
            rows.append(tmp_list)

        table.add(headers, rows).set_global_opts(
            title_opts=ComponentTitleOpts(title="当前持仓列表")
        )
        return table

    def table_date_holding_part_2(self) -> Table:
        table = Table()
        date_holding = self.get_date_holding(self.show_date)
        rows = list()
        headers = ["代码",
                   "名称",
                   "策略类型",
                   "操作逻辑",
                   "形态学分析",
                   "预期盈利",
                   "后续分析",
                   "卖出市值"]
        for item in date_holding['code_holding']:
            tmp_list = list()
            tmp_list.append(item['code'])
            tmp_list.append(item['name'])
            tmp_list.append(item['strategy'])
            tmp_list.append(item['logic'])
            tmp_list.append(item['patterns'])
            tmp_list.append(item['expect_profit_ratio'])
            tmp_list.append(item['analyze'])
            tmp_list.append(item['sell_value'])
            rows.append(tmp_list)

        table.add(headers, rows)
        return table

    def get_hs300_cur_ratio(self):
        fm  = FactorModule()
        fm_date_df = fm.get_single_stock_factors("000300","change_rate",True,self.last_5_date,self.cur_date)
        return fm_date_df

    def get_median(self):
        fm = FactorModule()
        fm_date_df = fm.get_single_stock_factors("000300", "change_rate", True, "2010-01-01", self.cur_date)
        fm_date_df.to_csv("hs300.csv")

        factor_cursor = DB_CONN['median'].find(
            {'date': {'$gte': "2010-01-01", '$lte': self.cur_date}},
            sort=[('date', 1)],
            projection={'_id': False})
        factor_df = pd.DataFrame([ x for x in factor_cursor])
        factor_df.to_csv("median.csv")

        return fm_date_df



    def table_date_holding_overview(self) -> Table:
        table = Table()
        dates = get_trading_dates(begin_date=self.last_5_date,end_date = self.show_date)
        hs300_change_rate = self.get_hs300_cur_ratio()
        rows = list()
        headers = ["日期",
                   "现金",
                   "持仓盈利",
                   "持仓市值",
                   "仓位",
                   "价值持仓",
                   "价值仓位",
                   "趋势持仓",
                   "趋势仓位",
                   "其他持仓",
                   "其他仓位",
                   "历史至今总投入",
                   "历史至今总收益",
                   "今年至今总收益",
                   #"历史至今收益率",
                   "当前总市值",
                   "当日盈利",
                   "当日盈利比例",
                   "沪深300当日涨跌幅"]

        total_profit = 0
        last_year_end_date_holding = self.get_date_holding("2020-12-31")

        for date in dates:
            date_holding = self.get_date_holding(date)
            data_list = list()
            data_list.append(date_holding['date'])
            data_list.append(round(date_holding['cash'],2))
            data_list.append(round(date_holding['holding_profit'],2))
            data_list.append(round(date_holding['holding_value'],2))
            data_list.append(date_holding['position'])
            data_list.append(date_holding['value_holding'])
            data_list.append(date_holding['value_position'])
            data_list.append(date_holding['trend_holding'])
            data_list.append(date_holding['trend_position'])
            data_list.append(date_holding['other_holding'])
            data_list.append(date_holding['other_position'])
            data_list.append(round(date_holding['total_cost'],2))
            data_list.append(round(date_holding['total_profit'],2))
            data_list.append(round(date_holding['total_profit'] - last_year_end_date_holding['total_profit'],2))
            #data_list.append(round(date_holding['total_profit_ratio'],2))
            data_list.append(round(date_holding['total_value'],2))
            data_list.append(date_holding['date_profit'])
            data_list.append(date_holding['date_profit_ratio'])
            data_list.append(float(hs300_change_rate.loc[hs300_change_rate['date']==date]['close_change_rate']))
            total_profit += date_holding['date_profit']
            rows.append(data_list)

        total_list = list()
        total_list.append('近日总计')
        total_list.append(round(date_holding['cash'], 2))
        total_list.append(round(date_holding['holding_profit'], 2))
        total_list.append(round(date_holding['holding_value'], 2))
        total_list.append(date_holding['position'])
        total_list.append(date_holding['value_holding'])
        total_list.append(date_holding['value_position'])
        total_list.append(date_holding['trend_holding'])
        total_list.append(date_holding['trend_position'])
        total_list.append(date_holding['other_holding'])
        total_list.append(date_holding['other_position'])
        total_list.append(round(date_holding['total_cost'], 2))
        total_list.append(round(date_holding['total_profit'], 2))
        total_list.append(round(date_holding['total_profit'] - last_year_end_date_holding['total_profit'], 2))
        #total_list.append(round(date_holding['total_profit_ratio'], 2))
        total_list.append(round(date_holding['total_value'], 2))
        total_list.append(round(total_profit,2))
        total_list.append(round(100*total_profit/(date_holding['total_value'] - total_profit),2))
        total_list.append('N/A')
        rows.append(total_list)

        table.add(headers, rows).set_global_opts(
            title_opts=ComponentTitleOpts(title="账户总览")
        )
        return table

    def liquid_cur_holding_pos(self) -> Liquid:
        date_holding = self.get_date_holding(self.show_date)
        position = round(date_holding['position']/100,2)
        c = (
            Liquid()
            .add("lq", [position, position])
            .set_global_opts(title_opts=opts.TitleOpts(title="当前仓位"))
        )
        return c

    def line_position(self):
        total_date_holding = self.get_total_date_holding(begin_date=self.begin_date,end_date=self.end_date)
        x_date = list()
        y_profit = list()
        for item in total_date_holding:
            x_date.append(item['date'])
            position = round(item['position'] / 100, 2)
            y_profit.append(position)
        c = (
            Line()
                .add_xaxis(x_date)
                .add_yaxis("历史仓位变化", y_profit,
                           markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),

                           )
                .set_global_opts(title_opts=opts.TitleOpts(title="历史仓位趋势图"))
        )
        return  c

    def line_profit(self,begin_date,end_date,title_name):
        total_date_holding = self.get_total_date_holding(begin_date=begin_date,end_date=end_date)
        x_date = list()
        y_profit = list()
        base_profit = total_date_holding[0]['total_profit']
        for item in total_date_holding:
            x_date.append(item['date'])
            if title_name == "历史总收益趋势图":
                y_profit.append(round(item['total_profit'], 2))
            else:
                y_profit.append(round(item['total_profit'] - base_profit, 2))

        c = (
            Line()
                .add_xaxis(x_date)
                .add_yaxis("历史总收益", y_profit,
                           markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),

                           )
                .set_global_opts(title_opts=opts.TitleOpts(title=title_name))
        )
        return  c

    def page_cur_holding(self):
        begin_time = time.time()
        table_date_holding_1 = self.table_date_holding_part_1()
        table_date_holding_2 = self.table_date_holding_part_2()
        table_date_holding_time = time.time()
        table_overview = self.table_date_holding_overview()
        table_overview_time = time.time()
        #begin_date = calc_negative_diff_dates(date=self.show_date,delta_days=-5)
        table_pattern = self.table_pattern_strategy_stocks()
        table_pattern_time = time.time()

        table_value = self.table_value_strategy_stocks()
        table_value_time = time.time()

        ret,table_block = self.table_best_block(self.show_date)
        table_block_time = time.time()
        choice_ret,choice_table_block = self.table_best_block_choice(self.show_date)
        choice_table_block_time = time.time()

        avg_choice_ret,avg_choice_table_block = self.table_avg_best_block_choice(self.show_date)
        avg_choice_table_block_time = time.time()

        liquid_holding_pos = self.liquid_cur_holding_pos()
        liquid_holding_pos_time = time.time()
        all_time_line_profit = self.line_profit(self.begin_date,self.end_date,"历史总收益趋势图")
        cur_month_line_profit = self.line_profit(self.last_month_end_date,self.end_date,f"{self.cur_month_begin_date[0:7]}月收益趋势图")
        cur_year_line_profit = self.line_profit(self.last_year_end_date,self.end_date,f"{self.cur_year_begin_date[0:4]}年收益趋势图")
        line_profit_time = time.time()
        line_position = self.line_position()
        line_position_time = time.time()
        #begin_date = calc_negative_diff_dates(date=self.show_date,delta_days=-30)
        table_trading_record = self.table_trading_record(self.cur_month_begin_date,self.cur_date)
        table_trading_record_time = time.time()
        page = Page()
        page.add(liquid_holding_pos,
                 table_overview,
                 table_date_holding_1, table_date_holding_2,
                 table_trading_record,
                 table_pattern)

        if choice_ret:
            page.add(choice_table_block)
        if avg_choice_ret:
            page.add(avg_choice_table_block)
        if ret:
            page.add(table_block)

        page.add(#table_value,
                 all_time_line_profit,
                 cur_month_line_profit,
                 cur_year_line_profit,
                 line_position)

        page.render()
        page_render_time = time.time()

        print(f"table_date_holding_time：{round(table_date_holding_time - begin_time,2)}\r\n"
              f"table_overview_time：{round(table_overview_time - table_date_holding_time,2)}\r\n"
              f"table_pattern_time： {round(table_pattern_time - table_overview_time,2)}\r\n"
              f"table_value_time： {round(table_value_time - table_pattern_time,2)}\r\n"
              f"table_block_time： {round(table_block_time - table_value_time,2)}\r\n"
              f"choice_table_block_time： {round(choice_table_block_time - table_block_time,2)}\r\n"
              f"avg_choice_table_block_time： {round(avg_choice_table_block_time - choice_table_block_time,2)}\r\n"
              f"liquid_holding_pos_time：{round(liquid_holding_pos_time - avg_choice_table_block_time,2)}\r\n"
              f"line_profit_time： {round(line_profit_time - liquid_holding_pos_time,2)}\r\n"
              f"line_position_time：{round(line_position_time - line_profit_time,2)}\r\n"
              f"table_trading_record_time：{round(table_trading_record_time - line_position_time,2)}\r\n"
              f"page_render_time: {round(page_render_time - table_trading_record_time,2)}")
        return page

    # def page_cur_strategy(self):
    #     t = self.bar_example()
    #     c = self.bar_example()
    #     page = Page()
    #     page.add(t,c)
    #     page.render()
    #     return page
    #
    # def bar_example(self):
    #     bar = Bar()
    #     bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    #     bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
    #     # render 会生成本地 HTML 文件，默认会在当前目录生成 render.html 文件
    #     # 也可以传入路径参数，如 bar.render("mycharts.html")
    #     return bar
    #
    # def tab_base(self):
    #     #tab = Tab()
    #     self.table_date_holding()
    #     #tab.add(self.page_cur_strategy(),"当日策略")
    #     #tab.add(self.bar_example(),"当日策略")
    #     #tab.add(self.page_base(),"当日持仓")
    #     #tab.add(self.page_base(),"当日持仓")
    #     #tab.render()

if __name__ == '__main__':
    #datetime_obj = datetime.now()
    #date = datetime_obj.strftime('%Y-%m-%d')
    pd.set_option('display.width',500)
    pd.set_option('display.max_columns', 500)
    pd.set_option('display.max_colwidth', 500)
    visual = Visual(begin_date="2019-09-01",end_date=None,show_date=None)
    visual.page_cur_holding()
    #visual.table_best_block_choice(end_date='2021-04-18')
    #visual.get_median()
    #visual.cal_avg_best_block_choice("2021-03-10")